package io.simple.core;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 *
 */
public class ClassSourceHandler implements SourceHandle{

    private static List<ClassHandle> handles = new LinkedList<ClassHandle>();
    private static ClassSourceHandler handler;

    /**
     * add ClassHandle
     * eg.
     * ```
     * ClassSourceHandler.addHandle(new ClassHandle() {
     *      @Override
     *      public void handle(Class clazz) {
     *          Bind bind = (Bind) clazz.getAnnotation(Bind.class);
     *          if(bind != null){
     *              System.out.println("bind :::::::: " + clazz.getName());
     *          }
     *      }
     * });
     * ```
     * @param handle
     * @return
     */
    public static ClassSourceHandler addHandle(ClassHandle handle){
        handles.add(handle);
        return handler;
    }

    public static ClassSourceHandler getInstance(){
        if (handler == null){
            handler = new ClassSourceHandler();
        }
        return handler;
    }

    /**
     * @see SourceHandle
     * @param source
     */
    @Override
    public void handle(File source) {
        String rootDir = new File(Thread.currentThread().getContextClassLoader().getResource(".").getPath()).getAbsolutePath();
        String sourcePath = source.getAbsolutePath();
        String className = sourcePath.replace(rootDir + "\\", "").replaceAll("\\\\", "\\.").replace(".class", "");
        Class clazz = null;
        boolean classExsit = true;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            classExsit = false;
            e.printStackTrace();
        }
        if(classExsit) for (ClassHandle handle: handles) handle.handle(clazz);
    }
}
